package com.mikhailenko.transportMVC.json;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.eclipse.persistence.jaxb.MarshallerProperties;

import com.mikhailenko.transportMVC.model.JsonEntity;


public class MyJsonWriter {

    public   JsonObject createJson(){
        return Json.createObjectBuilder().add("ES", Json.createObjectBuilder()
                .add("name", "es name"))
                .add("es id", 1).add("Layer", Json.createObjectBuilder()
                        .add("name", "layer name"))
                        .add("countOfBlocks", 3)
                        .add("Blocks", Json.createObjectBuilder()
                                .add("block_en",Json.createArrayBuilder()
                                        .add(Json.createObjectBuilder()
                                                .add("name", "block1")
                                                .add("countOfInputs", 3))
                                        .add(Json.createObjectBuilder()
                                                .add("name", "block2")
                                                .add("countOfInputs", "2")))).build();
    }

    
    public void writeJson(JsonObject json, File file){
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            JsonWriter jsonWriter = Json.createWriter(fileWriter);
            jsonWriter.write(json);
            jsonWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public void marshall(JsonEntity jsonEntity, File file){
        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(jsonEntity.getClass());
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
            marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
            marshaller.marshal(jsonEntity, file);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
}
